use base::client;
use lazy_static::lazy_static;
use real::{do_cmd, Lock};
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{instrument, warn};
use tracing_subscriber::prelude::*;
use warp::{hyper::body::Bytes, Filter};

#[instrument(skip_all, name = "main")]
#[tokio::main]
async fn main() {
    base::trace_warn!();

    lazy_static! {
        static ref LOCK: Lock = Arc::new(Mutex::new(()));
        static ref CLIENT: client::Client = client::Client::new();
    }

    let md = "real";
    let body = base::body!();

    let post_three = warp::path(md)
        .and(warp::path::param())
        .and(warp::path::param())
        .and(body)
        .and_then(move |cmd: String, key: String, data: Bytes| async {
            let lock = Arc::clone(&LOCK);
            do_cmd(data, cmd, key, &CLIENT, lock).await
        });

    let post = warp::post().and(post_three).with(base::cors!());

    let get = warp::get().map(move || format!("\nserve: {}\n\n", md));
    let opt = base::opt!();

    let route = get.or(opt).or(post);

    warn!("listening on 0.0.0.0:9984");

    warp::serve(route).run(([0, 0, 0, 0], 9984)).await;
}
